// src/store/modules/message.js
import { defineStore } from 'pinia'
import { useUserStore } from '../user/user'

export const useMessageStore = defineStore('message', {
  state: () => ({
    // 聊天会话列表（用于消息列表页的“聊天”标签）
    chatSessions: [],
    // 当前聊天的消息详情（用于聊天详情页）
    currentChatMessages: [],
    // 点赞消息列表
    likeMessages: [],
    // 评论消息列表
    commentMessages: [],
    // @我的消息列表
    atMessages: [],
    
    // 粉丝消息列表
    fanMessages: [],
  }),
  actions: {
    // ========== 聊天消息处理 ==========
    // 接收聊天消息（更新会话列表和当前聊天详情）
    addChatMessage(msg) {
      const { fromId: targetUserId } = msg
      // 更新会话列表
      const sessionIndex = this.chatSessions.findIndex(item => item.targetUserId === targetUserId)
      if (sessionIndex > -1) {
        this.chatSessions[sessionIndex] = {
          ...this.chatSessions[sessionIndex],
          lastMsg: msg.content,
          time: msg.createdAt,
          unreadCount: this.chatSessions[sessionIndex].unreadCount + 1
        }
      } else {
        this.chatSessions.unshift({
          targetUserId,
          targetUserNickname: msg.senderNickname,
          targetUserImg: msg.senderAvatar,
          lastMsg: msg.content,
          time: msg.createdAt,
          unreadCount: 1,
          type: 'chat'
        })
      }
      // 若当前在聊天详情页，更新当前聊天消息
      if (this.currentChatMessages.length > 0 && this.currentChatMessages[0]?.toId === targetUserId) {
        this.currentChatMessages.push(msg)
      }
    },
    // 发送聊天消息（本地优先更新，再发Socket）
    sendChatMessage(targetUserId, content) {
      const userStore = useUserStore()
      const userId = userStore.userInfo.userId
      const newMsg = {
        id: Date.now(),
        fromId: userId,
        toId: targetUserId,
        content,
        createdAt: new Date().toISOString(),
        isLocal: true
      }
      // 更新当前聊天消息（若在聊天页）
      if (this.currentChatMessages.length > 0 && this.currentChatMessages[0]?.toId === targetUserId) {
        this.currentChatMessages.push(newMsg)
      }
      // 更新会话列表
      const sessionIndex = this.chatSessions.findIndex(item => item.targetUserId === targetUserId)
      if (sessionIndex > -1) {
        this.chatSessions[sessionIndex] = {
          ...this.chatSessions[sessionIndex],
          lastMsg: content,
          time: newMsg.createdAt,
          unreadCount: 0
        }
      } else {
        this.chatSessions.unshift({
          targetUserId,
          targetUserNickname: '未知用户',
          targetUserImg: '/default-avatar.png',
          lastMsg: content,
          time: newMsg.createdAt,
          unreadCount: 0,
          type: 'chat'
        })
      }
      // 发送到Socket
      const sendMsg = {
        content,
        createdAt: new Date().toISOString(),
        fromId: userId,
        toId: targetUserId,
        userAvatar: userStore.userInfo.userAvatar,
        userNickname: userStore.userInfo.userNickname,
      }
      socket.emit('sendPrivateLetter', sendMsg)
    },
    // 初始化当前聊天的历史消息（进入聊天页时调用）
    initCurrentChat(userId, targetUserId) {
      // 调用接口获取历史聊天消息，示例：
      // const res = await getChatHistoryAPI(userId, targetUserId)
      // this.currentChatMessages = res.data
    },

    // ========== 点赞消息处理 ==========
    addLikeMessage(msg) {
      this.likeMessages.unshift(msg)
    },
    sendLike(likeData) {
      // 调用点赞接口或Socket发送，示例：
      // socket.emit('sendLike', likeData)
      this.addLikeMessage(likeData)
    },

    // ========== 评论消息处理 ==========
    addCommentMessage(msg) {
      this.commentMessages.unshift(msg)
    },
    sendComment(commentData) {
      // 调用评论接口或Socket发送，示例：
      // socket.emit('sendComment', commentData)
      this.addCommentMessage(commentData)
    },

    // ========== @我的消息处理 ==========
    addAtMessage(msg) {
      this.atMessages.unshift(msg)
    },
    sendAt(atData) {
      // 调用@接口或Socket发送，示例：
      // socket.emit('sendAt', atData)
      this.addAtMessage(atData)
    },

    // ========== 粉丝消息处理 ==========
    addFanMessage(msg) {
      this.fanMessages.unshift(msg)
    },
  }
})
